package com.megvii.corelib.components;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.megvii.corelib.R;

import java.util.List;

/**
 * Created by linyue on 15/12/25.
 */
public class IconTextView extends RelativeLayout
        implements View.OnClickListener, View.OnKeyListener, AdapterView.OnItemClickListener
{
    protected TextView titleText;

    protected ListView listView;

    protected IconTextAdapter adapter;

    protected IconTextListener listener;

    public IconTextView(Context context)
    {
        super(context);
        init(context, null);
    }

    public IconTextView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        init(context, attrs);
    }

    public IconTextView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs)
    {
        inflate(context, R.layout.icon_text_layout, this);
        titleText = (TextView) findViewById(R.id.icon_text_layout_title);
        listView = (ListView) findViewById(R.id.icon_text_layout_list);
        adapter = new IconTextAdapter(context);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        this.setOnClickListener(this);
        this.setOnKeyListener(this);
    }

    public void setTitleText(String text)
    {
        if (text != null)
        {
            titleText.setText(text);
        }
    }

    public void setData(List<Integer> iconRess, List<String> texts)
    {
        adapter.updateData(iconRess, texts);
    }

    public void setListener(IconTextListener listener)
    {
        this.listener = listener;
    }


    public void onClick(View view)
    {
        if (listener != null)
        {
            int id = view.getId();
            if (id == this.getId())
            {
                listener.onCancel();
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        Integer realPosition = (Integer) parent.getItemAtPosition(position);
        if (listener != null)
        {
            listener.onChoose(realPosition);
        }
    }

    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (listener != null)
        {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
            {
                listener.onCancel();
                return true;
            }
        }
        return false;
    }

    public interface IconTextListener
    {
        public void onChoose(int position);

        public void onCancel();
    }
}
